using CGF;
using LitJson;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(InputField))]
public class InputInviteCode : MonoBehaviour
{
    private InputField inputField;
    
    void Awake()
    {
        inputField =  GetComponent<InputField>();

        inputField.SetLongPressAction(async () =>
        {
            string pasteContent = await CopyAndPaste.GetPaste();
            if (string.IsNullOrEmpty(inputField.text) && pasteContent.Length >= 6 && pasteContent.Length <= 15)
            {
                inputField.text = pasteContent.Replace("__", "");
            }
        });

        InitData();
    }

    private async void InitData()
    {
        //从推广过来的验证码要自动填好,Web端不支持静默读取剪贴板填好，即使通过点击获取也会弹出粘贴菜单，所以Web端通过URL读取
        if (Define.IsWebGL && !Application.isEditor)
        {
            JsonData args = JSHelper.GetAllURLParameters();
            if (args != null && args.Contains("code"))
            {
                Debug.Log($"URL code={args["code"].ToString()}");
                inputField.text = args["code"].ToString().Replace("__", "");
                if (inputField.text.Length >= 6 && inputField.text.Length <= 15)
                {
                    inputField.enabled = false;
                }
            }
        }
        else
        {
            string pasteContent = await CopyAndPaste.GetPaste();
            Debug.Log($"剪贴板：{pasteContent}");
            if (pasteContent.Length >= 6 && pasteContent.Length <= 15 && pasteContent.StartsWith("__"))
            {
                inputField.text = pasteContent.Replace("__", "");
                if (inputField.text.Length >= 6 && inputField.text.Length <= 15)
                {
                    inputField.enabled = false;
                }
            }
        }
    }
}
